package com.maolong.delayedconsumer.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.maolong.delayedconsumer.domain.Order;
import com.maolong.delayedconsumer.domain.Storage;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private IOrderService service;
    @Autowired
    private IStorageService storageService;


    @Transactional
    @RabbitListener(queues = "delayed_queue")
    public void receiveMessage(String body, Channel channel, Message message) throws Exception {
        log.info("接收到消息：{}",body);
        Order order = service.getOne(new QueryWrapper<Order>().eq("id", body));
        if("no".equals(order.getStatus())){
            log.info("订单状态为no，未支付，进行库存回滚");
            //库存回滚
            UpdateWrapper<Storage> wrapper = new UpdateWrapper<>();
            wrapper.eq("name",order.getName());
            wrapper.setSql("count=count+1");
            storageService.update(wrapper);
        }else {
            log.info("订单状态为yes，已支付，进行订单处理");
        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            if(message.getMessageProperties().getRedelivered()){
                log.info("拒绝");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                log.info("重新投递");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }
    }
}
